//
//  SQShopViewController.m
//  pai
//
//  Created by pro on 14-11-7.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQShopViewController.h"
#import "SQGoodsListViewCell.h"
#import "SQGoodsContentViewController.h"
#import "MJRefresh.h"

@interface SQShopViewController ()

@end

@implementation SQShopViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"兑换"];
    
    [self getGoodsListInfo];
}

-(void)getGoodsListInfo
{
    [self showList];
}

-(void)showList
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(312, 144);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    
    self.myCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.MyNavigationBar.frame.origin.y-self.MyNavigationBar.frame.size.height) collectionViewLayout:flowLayout];
    self.myCollection.backgroundColor = [UIColor whiteColor];
    [self.myCollection registerClass:[SQGoodsListViewCell class] forCellWithReuseIdentifier:@"SQGoodsListViewCell"];
    [self.view addSubview:self.myCollection];
    
    self.myCollection.delegate = self;
    self.myCollection.dataSource = self;
    
    // 2.集成刷新控件
    [self addHeader];
    [self addFooter];
}
- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.myCollection addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [vc doActionupdata];
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
    
#warning 自动刷新(一进入程序就下拉刷新)
    [self.myCollection headerBeginRefreshing];
}
- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.myCollection addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [vc doActionLoadMore];
    }];
}
#pragma mark - Collection View Data Source
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataMArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"show");
    static NSString *cellIdentifier = @"SQGoodsListViewCell";
    SQGoodsListViewCell *cell = (SQGoodsListViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    product_item_t item;
    [[self.dataMArr objectAtIndex:indexPath.row]getValue:&item];
    [cell setItem:item];
    
    return cell;
};
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//设置顶部的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={9,20};
    return size;
}
//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(312,144);
}
//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    product_item_t item;
    [[self.dataMArr objectAtIndex:indexPath.row]getValue:&item];
    
    SQGoodsContentViewController *gvc = [[SQGoodsContentViewController alloc]init];
    
    SQGoodsListViewCell *cell = (SQGoodsListViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    gvc.imageDic = cell.imageDic;
    gvc.item = item;
    [gvc getInfo];
    
    [self.navigationController pushViewController:gvc animated:YES];
}
-(void)doActionupdata
{
    auct_list_t alist;
    alist.base.msgtype = 1019;
    alist.base.len = sizeof(alist);
    alist.base.error = 0;
    
    alist.count = 10;
    alist.offset = 0;
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&alist length:sizeof(alist)];
    
    [super sendData:msgData tag:1 withHUD:NO];
}
-(void)doActionLoadMore
{
    auct_list_t alist;
    alist.base.msgtype = 1019;
    alist.base.len = sizeof(alist);
    alist.base.error = 0;
    
    alist.count = 10;
    alist.offset = (int)self.dataMArr.count;
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&alist length:sizeof(alist)];
    
    [super sendData:msgData tag:2 withHUD:NO];
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == 1) {
        if (self.socketLength == 0) {
            auct_list_t alist;
            [data getBytes:&alist length:sizeof(auct_list_t)];
            if (alist.base.error != ACS_SUCCESS) {
                [self.myCollection headerEndRefreshing];
                return;
            }
            self.templength =  data.length;
            self.socketLength = alist.base.len;
        }
        else{
            self.templength += data.length;
        }
        if (self.socketTempData == nil) {
            self.socketTempData = [NSMutableData dataWithData:data];
        }else{
            [self.socketTempData appendData:data];
        }
        if (self.templength < self.socketLength) {
            [asyncSocket readDataWithTimeout:-1 tag:self.socketTag];
            return;
        }else{
            auct_list_t baseInfo;
            [self.socketTempData getBytes:&baseInfo length:sizeof(baseInfo)];
            self.dataMArr = nil;
            self.dataMArr = [NSMutableArray array];
            for (int i =0; i< baseInfo.count; i++) {
                product_item_t item;
                [self.socketTempData getBytes:&item range:NSMakeRange(self.socketTempData.length - (baseInfo.count - i)*sizeof(item) - 8,sizeof(item))];
                [self.dataMArr addObject:[NSValue value:&item withObjCType:@encode(struct product_item_t)]];
                NSLog(@"product_id:%d",item.product_id);
                NSLog(@"points:%d",item.points);
                NSLog(@"price:%d",item.price);
                NSLog(@"stock:%d",item.stock);
                NSLog(@"title:%s",item.title);
                NSLog(@"category:%s",item.category);
                NSLog(@"intro:%s",item.intro);
            }
            [self.myCollection headerEndRefreshing];
            //更新列表
            [self.myCollection reloadData];
        }
    }else if (tag ==2)
    {
        if (self.moresocketLength == 0) {
            auct_list_t alist;
            [data getBytes:&alist length:sizeof(auct_list_t)];
            if (alist.base.error != ACS_SUCCESS) {
                [self.myCollection footerEndRefreshing];
                return;
            }
            self.moretemplength =  data.length;
            self.moresocketLength = alist.base.len;
        }
        else{
            self.moretemplength += data.length;
        }
        if (self.moresocketTempData == nil) {
            self.moresocketTempData = [NSMutableData dataWithData:data];
        }else{
            [self.moresocketTempData appendData:data];
        }
        if (self.moretemplength < self.moresocketLength) {
            [asyncSocket readDataWithTimeout:-1 tag:self.socketTag];
            return;
        }else{
            auct_list_t baseInfo;
            [self.moresocketTempData getBytes:&baseInfo length:sizeof(baseInfo)];
            if (self.dataMArr == nil) {
                self.dataMArr = [NSMutableArray array];
            }
            for (int i =0; i< baseInfo.count; i++) {
                product_item_t item;
                [self.moresocketTempData getBytes:&item range:NSMakeRange(self.moresocketTempData.length - (baseInfo.count - i)*sizeof(item) - 8,sizeof(item))];
                [self.dataMArr addObject:[NSValue value:&item withObjCType:@encode(struct product_item_t)]];
            }
            [self.myCollection footerEndRefreshing];
            //更新列表
            [self.myCollection reloadData];
        }
    }
    
    
}
@end
